package com.minjie.service;

import com.minjie.mapper.UserMapper;
import com.minjie.pojo.User;
import com.minjie.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.minjie.utils.MD5Utils.getMD5;

@Slf4j
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    //添加用户
    @Transactional
    public void addUser(User user) {
        user.setPassword(getMD5(user.getPassword(),"我是一个盐"));
        userMapper.insertUser(user);
    }

    //用户登录
    public User login(User user) {
        User user1 = userMapper.findUserByUsername(user.getUsername());
        if (user != null) {
            // 验证密码
            String saltedPassword = getMD5(user.getPassword(), "我是一个盐");
            return saltedPassword.equals(user1.getPassword())?user1:null;
        }
        return null;
    }

    public User getUserInfoByToken(String token) throws Exception {

        // 解析Token获取用户名
        Claims claims = JwtUtils.parseJWT(token); // 解析JWT，获取Claims对象
        String username = (String) claims.get("username"); // 获取username字段的值

        // 根据用户名获取用户信息
        User user = userMapper.findUserByUsername(username);
        if (user == null) {
            throw new Exception("用户不存在");
        }
        return user;
    }
}
